package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.service.cargo.ExportProductService;
import cn.itcast.service.cargo.ExportService;
import cn.itcast.vo.ExportProductVo;
import cn.itcast.vo.ExportResult;
import cn.itcast.vo.ExportVo;
import cn.itcast.web.controller.BaseController;
import cn.itcast.web.utils.BeanMapUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/cargo/export")
public class ExportController extends BaseController {
    @Reference
    private ContractService contractService;

    @Reference
    private ExportService exportService;

    @Reference
    private ExportProductService exportProductService;

    /**
     * 作用：雄安是状态位1的购销合同
     * url:/cargo/export/contractList.do
     * 参数：无
     * 返回值：返回值合同管理页面 cargo/export-contractList
     */
    @RequestMapping("/contractList")
    public String contractList(@RequestParam(defaultValue = "1")int pageNum,@RequestParam(defaultValue = "5")int pageSize){
        ContractExample contractExample = new ContractExample();
        contractExample.setOrderByClause("create_time desc");
        contractExample.createCriteria().andCompanyIdEqualTo(getLoginCompanyId()).andStateEqualTo(1);
        PageInfo<Contract> pageInfo = contractService.findByPage(contractExample, pageNum, pageSize);
        request.setAttribute("pageInfo",pageInfo);
        return "cargo/export/export-contractList";
    }
    /*
         作用： 显示的所有报运单
         url :  /cargo/export/list.do
         参数： 无
         返回值：报运单的列表
      */
    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "5") int pageSize){
        ExportExample exportExample = new ExportExample();
        exportExample.setOrderByClause("create_time desc");
        exportExample.createCriteria().andCompanyIdEqualTo(getLoginCompanyId());
        PageInfo<Export> pageInfo = exportService.findByPage(exportExample, pageNum, pageSize);
        request.setAttribute("pageInfo",pageInfo);
        return "cargo/export/export-list";
    }

    /**
     *作用：进入新增包运单页面
     * url:/cargo/export/toExport.do
     * 参数：多个购销合同的id
     * 返回值：新增报运单的页面
     * 注意：页面提交了多个id的数据，我们接收这些id的方式有两种、
     * 1.我们可以使用字符串数组接收String[] id
     * 2.我们可以使用字符串接收 String id
     */
    @RequestMapping("/toExport")
    public String toExport(String id){
        request.setAttribute("id",id);
        return "cargo/export/export-toExport";
    }

    /*
  作用: 保存修改报运单
  url ： cargo/export/edit.do
  参数： Export 对象
  返回： 返回报运单列表页面
   */
    @RequestMapping("edit")
    public String edit(Export export){
        //购销合同的所属公司的id
        export.setCompanyId(getLoginCompanyId());
        //购销合同的所属公司的名字
        export.setCompanyName(getLoginCompanyName());
        //购销合同创建人
        export.setCreateBy(getLoginUser().getId());
        //购销合同创建人所属的部门
        export.setCreateDept(getLoginUser().getDeptId());
        if(StringUtils.isEmpty(export.getId())){
            //保存
            exportService.save(export);
        }else{
            //更新
            exportService.update(export);
        }
        return "redirect:/cargo/export/list.do";
    }

    /**
     * 作用：进入修改包运单的页面
     * url:cargo/export/toUpdate.do
     * 参数id 包运单的id
     * 返回：修改包运单页面
     */
    @RequestMapping("/toUpdate")
    public String toUpdate(String id){
        //查找出运单
        Export export = exportService.findById(id);
        request.setAttribute("export",export);
        //查找出包运单下面的所有商品
        ExportProductExample exportProductExample = new ExportProductExample();
        exportProductExample.createCriteria().andExportIdEqualTo(id);
        List<ExportProduct> exportProductList = exportProductService.findAll(exportProductExample);
        request.setAttribute("eps",exportProductList);
        return "cargo/export/export-update";


    }

    /**
     * 查看
     * url:/cargo/export/exportE.do?id="+id
     * 参数:id
     * 返回值：export-view
     */
    @RequestMapping("/toView")
    public String toView(String id){
        Export export = exportService.findById(id);
        request.setAttribute("export",export);
        return "cargo/export/export-view";

    }
    /**
     * url:cargo/export/submit.do?id="+id
     * 参数：id
     * 返回值：cargo/export/list.do
     */
    @RequestMapping("/submit")
    public String submit(String id){
        Export export = exportService.findById(id);
        export.setState(1);
        exportService.update(export);
        return "redirect:/cargo/export/list.do";
    }
    /**
     * 取消报运单
     * url:/cargo/export/cancel.do?id="+id
     * 参数：id
     *返回值：redirect:/cargo/export/list.do
     */
    @RequestMapping("/cancel")
    public String cancel(String id){
        Export export = exportService.findById(id);
        export.setState(0);
        exportService.update(export);
        return "redirect:/cargo/export/list.do";
    }

    /**
     * url:/cargo/export/exportE.do?id="+id;
     * 电子报运
     * 参数：id
     * 返回值：cargo/export/export-toExport
     */
    @RequestMapping("/exportE")
    public String exportE(String id){
        Export export = exportService.findById(id);
        //把报运单的信息拷贝到exportVo对象中，其中这里有一个大坑：要求exportVo的id必须exportId要一直
        ExportVo exportVo = new ExportVo();
        BeanUtils.copyProperties(export,exportVo);
        //所属报运单
        exportVo.setExportId(export.getId());
        //根据报运单id查找所有的报运商品
        ExportProductExample exportProductExample = new ExportProductExample();
        exportProductExample.createCriteria().andExportIdEqualTo(id);
        List<ExportProduct> exportProductList = exportProductService.findAll(exportProductExample);
        for (ExportProduct exportProduct : exportProductList) {
            ExportProductVo exportProductVo = new ExportProductVo();
            BeanUtils.copyProperties(exportProduct,exportProductVo);
            //所属的报运单

            exportProductVo.setExportId(export.getId());
            exportProductVo.setExportProductId(exportProduct.getId());
            //把exportProductVo对象添加到exportVo
            exportVo.getProducts().add(exportProductVo);
        }
        //把exportvo对象交给海关平台去审核
        WebClient.create("http://localhost:9090/ws/export/user").post(exportVo);
        //调用海关平台的webService接口，去看当前包运单的审核的结果
        ExportResult exportResult = WebClient.create("http://localhost:9090/ws/export/user/" + id).get(ExportResult.class);
        //把审核的结果信息更新到本地的报运单表中
        exportService.updateByResult(exportResult);


        return "redirect:/cargo/export/list.do";
    }
    /**
     * 作用：现在报运单
     * url:/cargo/export/exportPdf.do?id=${o.id}
     * 参数：报运单的id
     * 返回：无下，因为要下载
     */
    @RequestMapping("/exportPdf")
    @ResponseBody
    public void exportPdf(String id) throws JRException, IOException {
        //通知浏览器以文件下载的方式处理内容
        response.setHeader("content-disposition","attachment;filename=export.pdf");

        //1. 找到模板的输入流
        InputStream inputStream = session.getServletContext().getResourceAsStream("/jasper/export.jasper");

        //根据报运单id找到报运单
        Export export = exportService.findById(id);
        //需要把export的对象转换为Map， key：属性名  value：属性值
        Map<String, Object> map = BeanMapUtils.beanToMap(export);


        //找到报运单的商品数据
        ExportProductExample exportProductExample = new ExportProductExample();
        exportProductExample.createCriteria().andExportIdEqualTo(id);
        List<ExportProduct> list = exportProductService.findAll(exportProductExample);
        //把list的数据放入数据源中
        JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(list);
        JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream, map, dataSource);

        //3. 把pdf输出
        JasperExportManager.exportReportToPdfStream(jasperPrint,response.getOutputStream());

    }


}
